const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   * KEY 和 SECRET 需要配置 **************************
   */
  data: {
    APP_KEY: "8wjMTUANpNuSeAGC2bGA3yV9",
    APP_SECRET: "iWK476LwxF0As8dA8mvC6eKSiLMWCS98",
    token: "",
    height: 0,
    position: "back",
    src: ""
  },

  authorize: function () {
    const that = this
    wx.authorize({
      scope: 'scope.camera',
      fail(res) {
        wx.showModal({
          title: '主人，小萌什么都看不见了',
          content: '(ノへ`、)请问主人愿意借手机相机用一下吗？',
          showCancel: "true",
          cancleText: "不愿意",
          confirmText: '可以呀',
          success(res) {
            if (res.confirm) {
              // 微信不支持二次直接弹窗发起授权（否则会一直fail），所以弹窗授权失败后，只能调opensetting去官方给的页面里设置
              wx.openSetting({
                success(res) {
                  if (!res.authSetting.camera) {
                    wx.navigateBack({})
                  }
                }
              })
            }
            else if (res.cancel) {
              wx.navigateBack({})
            }
          }
        })
      }
    })
  },


  onLoad: function (options) {
    const that = this
    const sysinfo = wx.getSystemInfoSync()
    that.setData({
      height: sysinfo.screenHeight,
    })
    wx.getSetting({
      success(res){
        if (!res.authSetting['scope.camera']){
          that.authorize()
        }
      }
    })
  /* demo专用数据
    var pet = {
    figure: "中型",
    friend: "非常友善",
    hair: "不掉毛",
    height: "不详cm",
    hot: 1,
    image: "cloud://pethub-database.7065-pethub-database-1301811252/cat/英国短毛猫.jpg",
    name: "英短",
    _id: "OlVYDYdzwGJDxGD9UrtPgryG7T03XJWwon0MeSVFl0GxJG0E"
    }*/
  },
  back(){
    wx.navigateBack({})
  },
  reverse() {
    this.setData({
      position: this.data.position === "back" ? "front" : "back"
    });
  },
  takePhoto() {
    var that = this;
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath
        }, () => {
          that.getFaceInfo();
        })
      }
    })
  },
  choosePhoto() {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original'],
      sourceType: ['album'],
      success(res) {
        // console.log(res);
        if (res.errMsg === "chooseImage:ok" &&
          res.tempFilePaths.length > 0) {
          that.setData({
            src: res.tempFilePaths[0]
          }, () => {
            that.getFaceInfo();
          })
        }
      }
    })
  },
  reChoose() {
    this.setData({
      src: "",
      pet: "",
      token: ""
    })
  },

  getFaceInfo() {
    wx.showLoading({
      title: '正在识别请稍后',
    });
    var that = this;
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + that.data.APP_KEY + "&client_secret=" + that.data.APP_SECRET,
      success: (res) => {
        that.data.token = res.data.access_token
        that.submitRequest();
      }
    })
  },
  submitRequest() {
    var that = this;
    const parms = {
      image: "",
      image_type: "BASE64",
      // face_field: "age,beauty,expression,gender,glasses,emotion"
    };
    const fileManager = wx.getFileSystemManager();
    fileManager.readFile({
      filePath: that.data.src,
      encoding: "base64",
      success: (res) => {
        parms.image = res.data;
        wx.request({
          url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=' + that.data.token,
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: parms,
          success: (res) => {
            // 使用shift()可以获取数组第一条数据
            console.log(res);
            wx.hideLoading();
            if (res.errMsg === "request:ok" && res.data.result !== null) {
              if(res.data.result[0].name.includes("猫")){var field = 'cat'}
              else if (res.data.result[0].name.includes("犬")){var field = 'dog'}
              // 存在API识别出结果，但数据库找不到宠物资料的情况
              else{
                if (res.data.result[0].name=="非动物"){
                  that.setData({
                    pet: { name: "我读书少不知道这是什么鬼(ノへ￣、)" }
                  })
                }
                else{
                  that.setData({
                    pet: { name: res.data.result[0].name+"!!没错吧≖‿≖✧" }
                  })
                }
                return null
              }
              db.collection(field).where(db.command.or([
                {term: db.command.in([res.data.result[0]['name']])
              },
                { name: db.command.in([res.data.result[0]['name']]) }
              ])).get()
                .then(info=>{
                  console.log(info)
                  // 存在API识别出结果，但数据库找不到宠物资料的情况
                  if(info.data.length==0){
                    that.setData({
                      pet: { name: res.data.result[0].name + "!!没错吧≖‿≖✧" }
                    })
                  }
                  else{
                    that.setData({
                      pet: info.data[0]
                    })
                  }
                })
            }
          },
        })
      }
    })
  }

})